package bintree.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Num145houxudiedai {
    public List<Integer> postorderTraversal(TreeNode root) {

        List<Integer> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        TreeNode cur = root;

        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            // 1.先一路向左走到底
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 2.查看当前栈顶元素的情况
            cur = stack.pop();
            if (cur.right == null || cur.right == prev) {
                ret.add(cur.val);
                prev = cur;
                cur = null;
            } else {
                stack.push(cur);
                cur = cur.right;
            }
        }
        return ret;
    }
}
